<?php
require_once 'copperforest.commons.php';


//CAMBIAMOS EL CLASSPATH POR EL DEL BUILD POR DEFECTO
if( !empty( $_SERVER[ 'CF_INI' ][ 'build.default' ] )  && is_dir( CF_BUILD_PATH . $_SERVER[ 'CF_INI' ][ 'build.default' ] . DIRECTORY_SEPARATOR . 'src' ) ){ //Si existe build defautl y es distinto de 0
    $_SERVER[ 'CF_BUILD' ] = $_SERVER[ 'CF_INI' ][ 'build.default' ];
}



if ( CF_HTTP_MODE ) {//Estamos via protocolo http (no consola), buscamos usuario
    
    
    define( 'CF_HTTP_PATH',
            ( dirname( $_SERVER[ 'SCRIPT_NAME'] ) == '/' ) ? '' : dirname( $_SERVER[ 'SCRIPT_NAME'] )   ); //dirname?
            
    define( 'CF_HTTP_BASE',
            'http'. ( empty( $_SERVER[ 'HTTPS' ] ) ? '' : 's' ) . '://' . ( empty( $_SERVER[ 'HTTP_HOST' ] ) ? $_SERVER[ 'SERVER_ADDR' ] : $_SERVER[ 'HTTP_HOST' ] ). ':' . $_SERVER[ 'SERVER_PORT' ]  );
    
    //I don't know why but when the htaccess  is in the document_root directory the apache doesn't define PATH_INFO
    /*
    $positionQuestionMark = strpos( $_SERVER[ 'REQUEST_URI' ], '?' );
    if( $positionQuestionMark === false) {
        $positionQuestionMark = strlen( $_SERVER[ 'REQUEST_URI' ] );
    }
    
    $pathInfo = substr( $_SERVER[ 'REQUEST_URI' ], 0, $positionQuestionMark );
    $_SERVER[ 'PATH_INFO' ] = '/' . substr( $pathInfo, strlen( CF_HTTP_PATH ) + 1 );
    
    
    unset( $pathInfo, $positionQuestionMark );
    */
    
    if ( !function_exists( 'apache_request_headers' ) ) {

        $headerArray = array( );
        foreach ( $_SERVER as $key => $value )
                if ( substr( $key, 0, 5 ) == 'HTTP_' )
                    $headerArray[ str_replace( ' ', '-',
                                ucwords( str_replace( '_', ' ',
                                                strtolower( substr( $key, 5 ) ) ) ) ) ] = $value;

        $_SERVER[ 'HTTP_HEADERS' ] = $headerArray;

        unset( $headerArray );
        
    }
    else $_SERVER[ 'HTTP_HEADERS' ] = apache_request_headers();

    if ( in_array( strtoupper( $_SERVER[ 'REQUEST_METHOD' ] ),
                    array( 'DELETE', 'PATCH', 'PUT' ) ) && substr( $_SERVER[ 'HTTP_HEADERS' ][ 'Content-Type' ],
                    0, 33 ) == 'application/x-www-form-urlencoded' )
            parse_str( file_get_contents( 'php://input' ), $_POST ); //SI NO HAY METODO POST EXISTE VARIABLE $_POST???
    
   
   //Buscamos el sesssion handler adecuado para aaveriguar el id 
    $sessionArray = array( );
    
    foreach ( $_SERVER[ 'CF_INI' ] as $key => $value ) {

        if ( substr( $key, 0, 8 ) == 'session.' ) {

            $matches = array( );

            if ( preg_match( '/^session\.(\d+).*$/', $key, $matches ) ) {
                $num = $matches[ 1 ];

                if ( !isset( $sessionArray[ $num ] ) ) {
                        $sessionArray[ $num ] = array( );
                }

                //if( $key == 'session.' . $num . '.realm.domain' )
                if ( substr( $key, -13 ) == '.realm.domain' ) {
                        $sessionArray[ $num ][ 'realm.domain' ] =  $value;
                }

                else if ( substr( $key, -11 ) == '.realm.path' ) {

                    if ( substr( $value, 0, 1 ) !== '/' ) {
                            $value = '/' . $value;
                    }

                    $sessionArray[ $num ][ 'realm.path' ] = $value;
                }
                else if ( substr( $key, -13 ) == '.save_handler' ) {
                        $sessionArray[ $num ][ 'save_handler' ] =  $value;
                }
                else if ( substr( $key, -11 ) == '.expiration' ) {
                        $sessionArray[ $num ][ 'expiration' ] = ( int ) $value;
                }
                else if ( substr( $key, -16 ) == '.allow_anonymous' ) {
                        $sessionArray[ $num ][ 'allow_anonymous' ] =  $value;
                }
                else if ( substr( $key, -18 ) == '.cookie_expiration' ) {
                        $sessionArray[ $num ][ 'cookie_expiration' ] =  $value;
                }
            }
        }
    }
        
    
    $theSession = null;
    $theSessionNumber = null;
    // $theSessionPathArray = array();

    if( preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $_SERVER[ 'HTTP_HOST' ] ) ){
        $httpSubdomainArray = array( $_SERVER[ 'HTTP_HOST' ] );
        $httpSubdomainArrayLength = 1;
    }
    else{
        $httpSubdomainArray = explode( '.', $_SERVER[ 'HTTP_HOST' ] ); //Y si es una dirección IP???
        $httpSubdomainArrayLength = count( $httpSubdomainArray );
    }

    $httpSubpathArray = explode( '/', CF_HTTP_PATH );
    $httpSubpathArrayLength = count( $httpSubpathArray );

    $subdomainMatchedLength = $httpSubdomainArrayLength;
    $subpathMatchedLength = $httpSubpathArrayLength;

    //voy acotando $subdomainArrayLength
    foreach ( $sessionArray as $k => $s ) {

        if( preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/', $s[ 'realm.domain' ] ) ){
            $subdomainArray = array( $s[ 'realm.domain' ] );
            $subdomainArrayLength = 1;
        }
        else{
            $subdomainArray = explode( '.', $s[ 'realm.domain' ] ); //Y si es una dirección IP???
            $subdomainArrayLength = count( $subdomainArray );
        }

        if ( $subdomainMatchedLength >= $subdomainArrayLength ) {

            $match = true;

            for ( $i = 0; $i < $subdomainArrayLength; $i++ ) {
                if ( $httpSubdomainArray[ $i ] != $subdomainArray[ $i ] ) {
                    $match = false;
                    break;
                }
            }

            if ( $match ) {

                $subpathArray = explode( '/', $s[ 'realm.path' ] );
                $subpathArrayLength = count( $subpathArray );

                if ( $subpathMatchedLength >= $subpathArrayLength ) {

                    for ( $i = 0; $i < $subpathArrayLength; $i++ ) {

                        if ( $httpSubpathArray[ $i ] != $subpathArray[ $i ] ) {
                            $match = false;
                            break;
                        }
                    }

                    if ( $match ) { //aqui coinciden tanto dominios como path, pero tengo que seguir buscando por si hay alguno más especifico
                        $theSession = $s;
                        $theSessionNumber = $k;
                        // $theSessionPathArray = $subpathArray;

                        $subdomainMatchedLength = $subdomainArrayLength;
                        $subpathMatchedLength = $subpathArrayLength;
                    }
                }
            }
        }
    }
    
    if ( !empty( $theSession ) ) {

            //EL Session save handler deberá autoconfigurarse
            //Establecer su path, su domain, para redistribuirse y su expiration
            //start de session
        
            $_SESSION = new $theSession[ 'save_handler' ]( $theSessionNumber );

            register_shutdown_function( array( $_SESSION, 'writeClose' ) ); //por si acaso la otra no llega a ejecutarse
            
            //Ahora aqui debería buscar un build distinto
            $userId = $_SESSION->getUserId();

            
            //Que razones habria para cambiar de usuario, pues de anonimo a logueado
            if ( !isset( $_SESSION[ 'CF_USER_ID' ] ) || $_SESSION[ 'CF_USER_ID' ] != $userId || !isset( $_SESSION[ 'CF_BUILD' ] )  ) { //si no cambio el usuario y hay establecido un build en session seguimos utilizandolos

                $userArray = array( );

                foreach ( $_SERVER[ 'CF_INI' ] as $key => $value ) {

                    if ( substr( $key, 0, 6 ) == 'build.' ) {

                        $matches = array( );

                        if ( preg_match( '/^build\.(\d+).*$/', $key, $matches ) ) {
                            $num = $matches[ 1 ];

                            if ( !isset( $userArray[ $num ] ) )
                                    $userArray[ $num ] = array( );

                            if ( substr( $key, -12 ) == '.min_user' )
                                    $userArray[ $num ][ 'min_user' ] = ( int ) $value;

                            else if ( substr( $key, -12 ) == '.max_user' )
                                    $userArray[ $num ][ 'max_user' ] = ( int ) $value;

                            else if ( substr( $key, -11 ) == '.user_array' )
                                    $userArray[ $num ][ 'user_array' ] = explode( ',', $value );

                        }
                    }
                }
                
                krsort ( $userArray );//empezamos por los nuevos
                
                if ( !empty( $userArray ) ) {
                    
                    foreach( $userArray as $b => $users ){
                        
                        if( isset( $users[ 'user_array'] ) && in_array( $userId, $users[ 'user_array' ] ) ) {
                            $_SERVER[ 'CF_BUILD' ] = $b;
                            break;
                        }
                        else if( isset( $users[ 'max_user' ] ) ){
                            
                            if( $users[ 'max_user'] >= $userId ){
                                
                                if( isset( $users[ 'min_user' ] ) ) {
                                    if( $users[ 'min_user'] <= $userId ) {
                                        $_SERVER[ 'CF_BUILD' ] = $b;
                                        break;
                                    }
                                }
                                else{
                                    $_SERVER[ 'CF_BUILD' ] = $b;
                                    break;
                                }
                            }
                            
                        }
                        else if( isset( $users[ 'min_user' ] ) && $users[ 'min_user' ] >= $userId && $users[ 'min_user' ] <= $userId ) {
                            $_SERVER[ 'CF_BUILD' ] = $b;
                            break;
                        }
                        
                    }

                }
                
            }
            
            $_SESSION[ 'CF_USER_ID' ] = $userId;
            $_SESSION[ 'CF_BUILD' ] = $_SERVER[ 'CF_BUILD' ]; //en toda la session siempre utilizaremos el mismo build
            unset(  $userId );
     }
     else {
        session_start ( );
     }
     
     //    $theSessionPath = '/' . implode( '/', $theSessionPathArray );

    unset( $sessionArray, $httpSubdomainArray, $httpSubdomainArrayLength,
            $httpSubpathArray, $httpSubpathArrayLength, $match, $subdomainArray,
            $subdomainArrayLength, $subpathArray, $subpathArrayLength, $theSession ); //, $theSessionPathArray
    
    
    
}
//Si aqui hay un error que pasa? De hecho tiene que haber un error al crear el objeto SESSION!!!


if( empty( $_SERVER[ 'CF_BUILD' ] ) ) {
    
    define( 'CF_CLASS_PATH', CF_BASE_PATH . 'app' . DIRECTORY_SEPARATOR . 'src'  . DIRECTORY_SEPARATOR );
    define( 'CF_RESOURCES_PATH', CF_BASE_PATH . 'app' . DIRECTORY_SEPARATOR . 'resources'  . DIRECTORY_SEPARATOR );
    
    if( !file_exists( CF_BUILD_PATH . '0' ) ) { 
        mkdir( CF_BUILD_PATH . '0' );
        chmod( CF_BUILD_PATH . '0' , 0777 );
    }
    
    if ( !file_exists( CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'log'  . DIRECTORY_SEPARATOR ) ){
        mkdir( CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'log'  . DIRECTORY_SEPARATOR, 0777 );
        chmod( CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'log'  . DIRECTORY_SEPARATOR, 0777 );
    }

    if ( !file_exists(  CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'config'  . DIRECTORY_SEPARATOR ) ){
        mkdir(  CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'config'  . DIRECTORY_SEPARATOR, 0777 );
        chmod(  CF_BUILD_PATH . '0' . DIRECTORY_SEPARATOR . 'config'  . DIRECTORY_SEPARATOR, 0777 );
    }

    $_SERVER[ 'CF_TIME' ] = time();
}
else {
    
    $_SERVER[ 'CF_TIME' ] = file_get_contents( CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'build.time' );
    
    //AQUI tienen que estar creada la estructura de directorios, log, temp, config, resources, además del src
    define( 'CF_CLASS_PATH', CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'src'  . DIRECTORY_SEPARATOR );
    define( 'CF_RESOURCES_PATH', CF_BUILD_PATH . $_SERVER[ 'CF_BUILD' ] . DIRECTORY_SEPARATOR . 'resources'  . DIRECTORY_SEPARATOR );
   

}

//dependiendo de que  funcion se esté utilizando la quito y pongo la definitiva con la constante CF_CLASS_PATH
$functions = spl_autoload_functions();
if(in_array('cfFrameworkSrcClassPath',$functions)){
    spl_autoload_unregister( 'cfFrameworkSrcClassPath' );
}
if(in_array('cfFrameworkDefaultClassPath',$functions)){
    spl_autoload_unregister( 'cfFrameworkDefaultClassPath' );
}
unset($functions);

function cfFrameworkClassPath( $className )
{
   require_once( CF_CLASS_PATH . str_replace( "\\", DIRECTORY_SEPARATOR,
                   $className ) . '.class.php');
}

spl_autoload_register( 'cfFrameworkClassPath' );